<?php
session_start();
require 'listingLogic.php';
checkLoggedIn();

$addionalInfoExists = additionalInformationExists($_SESSION['userLoggedIn']);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
	<link rel="stylesheet" type="text/css" href="css/fontFaces.css" media="screen" />
	<style type="text/css">
		html{
			font-family: 'ralewaysemibold';
			font-size: 14px;
		}
		label{
			background-color: #bfbfbf;
		}
		#personalInfo{
			width: 100%;
			height: 50px;
			position: absolute;
			top: 0;
		}
		#personalInfo > div{
			display: inline-block;
		}
		#personalInfo #profileImageContainer{
			height: 100%;
			width: 50px;
		}
		#personalInfo #profileImageContainer img{
			width: 100%;
			height: 100%;
		}
		#personalInfo #profileImageContainer #infoContainer{
			width: 100%;
			height: 100%;
		}
		div[id$="Previewer"]{
			height: 200px;
			width: 200px;
			background-size: contain;
			border: 1px solid gray;
			background-repeat: no-repeat;
			display: none;
		}

		#listingFormContainer{
			position: absolute;
			top: 60px;
		}
	</style>
	<script src="js/jquery-1.7.1.min.js"></script>
  	<script src="js/jquery-ui-1.8.18.custom.min.js"></script>
  	<script src="js/jspostcode.js"></script>
  	<script src="js/util.js"></script>
	<script type="text/javascript">
		var hiddenElements = [];
		function showThumbnail()
	    {
	        var files = !!this.files ? this.files : [];
	        var previewerId = "#" + $(this).attr("id") + "Previewer";
	        if (!files.length || !window.FileReader){
	        	hideElements([previewerId]);
	        	return; // no file selected, or no FileReader support
	        } 
	 
	        if (/^image/.test( files[0].type)){ // only image file
	            var reader = new FileReader(); // instance of the FileReader
	            reader.readAsDataURL(files[0]); // read the local file
	 			
	            reader.onloadend = function(){ // set image data as background of div
	                $(previewerId).css("background-image", "url("+this.result+")");
	                $(previewerId).css("display", "block");
	            }
	        }else{
	        	hideElements([previewerId]);
	        }
	    }
		function initialize(){
			$("#postcode").on("change",function(){
				debugger;
				var postcode = $(this).val().trim();
				if(validatePostCode(postcode)){
					getAddress(postcode, showAddress);
				}else{
					alert("Not a valid postcode");
				}
			});
			$("#postcodeListing").on("change", function(){
				var displayDividedAddress = function(result){
					$("#coordsLatListing").val(result[1].geometry.location.lat);
					$("#coordsLngListing").val(result[1].geometry.location.lng);
					debugger;
					$("#cityListing").val(result[0]['address_components'][3]['long_name']);
					$("#areaListing").val(result[0]['address_components'][2]['long_name']);
					$("#streetNameListing").val(result[0]['address_components'][1]['long_name']);
					$("#houseNumberListing").val(result[0]['address_components'][0]['long_name']);
				};
				var postcode = $(this).val().trim();
				var saveCoords = function(lat, lng){

				}
				if(validatePostCode(postcode)){
					getAddress(postcode, displayDividedAddress);
				}else{
					alert("Not a valid postcode");
				}
			});
			$("#listingFormBody").css("display", "none");
			$("#typeofListing").on("change", displayForm);
			$("#typeofListing").trigger("change");
			$("input[type=file]").each(function (){
				$(this).on("change", showThumbnail);
			});
			debugger;
			if($("#completionForm")){
				$("#completionForm").on("submit", validateForm);
			}
			$("#cancellationListing").on("change", onChangeCancellation);
			$("#cancellationListing").trigger("change");
		}

		function displayForm(){
			debugger;
			displayListingElement(hiddenElements);
			clearArray(hiddenElements);
			var elementsToHide = [];
			var typeofListing = $(this).val();
			switch(typeofListing){
				case "1":
					elementsToHide = ["hotelRatingListing","hotelRulesListing", "openingTimeListing", "cancellationFeeListing"];
					break;
				case "2":
					elementsToHide = ["extraPeopleListing","houseRulesListing", "openingTimeListing","weekPriceListing", "monthPriceListing", "bedroomsListing", "cancellationFeeListing"];
					break;
				case "3":
					elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
					 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
					 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
					 "hotelRatingListing"];
					break;
				case "4":
					elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
					 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
					 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
					 "hotelRatingListing"];			
					 break;
				case "5":
					elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
					 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
					 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
					 "hotelRatingListing"];
					 break;
				default:
					$("#listingFormBody").css("display", "none");
					break;
			}
			hideElements(elementsToHide);
			if(typeofListing && typeofListing !== ""){
				$("#listingFormBody").css("display", "block");
			}
		}

		function onChangeCancellation(){
			var cT = $(this).val();
			var cancellationFee = $("#cancellationFeeListing");
			debugger;
			if(cT !== "" && cT !== "none"){
				showListingElement("cancellationFeeListing");
			}else{
				hideListingFormElement("cancellationFeeListing");
			}
		}

		function showAddress(result){
			var resultStr = "";
			result = result[0]['address_components'];
			for(var i = 0; i<result.length; i++){
				resultStr += " " + result[i]['long_name'];
			}
			$("#address").val(resultStr);
		}
		function getAddress(postcode, outputFunction, coordsFunction){
			var result = "";
			$.post('http://maps.googleapis.com/maps/api/geocode/json?address='+postcode+'&sensor=false', function(r) {
					debugger;
					if(!r['results'][0]){
						outputFunction("Please type your address here");
						return;
					}
					var lat = r['results'][0]['geometry']['location']['lat'];
					var lng = r['results'][0]['geometry']['location']['lng'];
					if(coordsFunction){
						coordsFunction(lat, lng);
					}
					$.post('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lng+'&sensor=false', function(address) {
						result = address['results'];
						/*result = address['results'][0]['address_components'][0]['long_name'];
						result += " " + address['results'][0]['address_components'][1]['long_name'];
						result += " " + address['results'][0]['address_components'][2]['long_name'];
						result += " " + address['results'][0]['address_components'][3]['long_name'];*/
						outputFunction(result);
					});
				});
			return result;
		}
		function hideElements(elementsToHide){
			for(var i = 0; i<elementsToHide.length; i++){
						hideListingFormElement(elementsToHide[i]);
			}
		}
		function hideListingFormElement(id){
			var label = $("label[for='"+id+"']");
			var element = $("#"+id);
			label.css("display", "none");
			element.css("display", "none");
			hiddenElements.push(id);
		}

		function displayListingElements(listingElementsToShow){
			for(var i = 0; i<listingElementsToShow.length; i++){
				showListingElement(listingElementsToShow[i]);
			}
		}

		function showListingElement(id){
			var label = $("label[for='"+id+"']");
			var element = $("#"+id);
			label.css("display", "initial");
			element.css("display", "initial");
		}

		$(document).ready(initialize);

		function validateForm(){
			debugger;
			var message = "";
			var errMessages = [];
			errMessages.push(validateField("firstName", ["empty","textonly"]));
			errMessages.push(validateField("secondName", ["textonly"]));
			errMessages.push(validateField("firstLastname", ["empty","textonly"]));
			errMessages.push(validateField("secondLastname", ["textonly"]));
			errMessages.push(validateField("firstName", ["empty","textonly"]));
			errMessages.push(validateField("postcode", ["empty","postcode"]));
			errMessages.push(validateField("address", ["empty"]));
			errMessages.push(validateField("dateOfBirth", ["empty", "dateOfBirth"]));
			debugger;
			message = concatArray(message, errMessages);
			if(message.trim() !== ""){
				alert(message);
				return false;
			}
		}

		function validateListingForm(){

		}

	</script>
</head>
<body>
	<?php
		if(!$addionalInfoExists){
	?>
	<div class="completionForm">
		<h1>We're almost there. Please fill out the information below:</h1>
		<div id="formContainer">
			<form enctype="multipart/form-data" method="post" action="accountValidator.php" id="completionForm">
				<!-- USER NAME -->
				<fieldset>
					<legend>Name</legend>
					<label for="firstName">First Name:</label>
					<input id="firstName" name="firstName" type="text"/>
					<label for="secondName">Second Name:</label>
					<input id="secondName" name="secondName" type="text"><br>
					<label for="firstLastname">First Family Name:</label>
					<input id="firstLastname" name="firstLastname" type="text"/>
					<label for="secondLastname">Second Family Name:</label>
					<input id="secondLastname" name="secondLastname" type="text">
				</fieldset>
				<!-- ADDRESS UK ONLY-->
				<fieldset>
					<legend>Address</legend>
					<label for="postcode">Postcode:</label>
					<input type="text" name="postcode" id="postcode"/>
					<label for="address">Address: </label>
					<input type="text" name="address" id="address" />
				</fieldset>
				<!-- OPTIONAL INFO -->
				<fieldset>
					<legend>Additional Info</legend>
					<label for="gender">Gender:</label>
					<input type="radio" name="gender" id="genderM" value="1">Male</input>
					<input type="radio" name="gender" id="genderF" value="2">Female</input>
					<label for="dateOfBirth">Date of birth:</label>
					<input type="date" name="dateOfBirth" id="dateOfBirth"/>
				</fieldset>
				<!-- IMAGE -->
				<fieldset>
					<legend>Images</legend>
					<div id="primaryImagePreviewer">
					</div>
					<label for="primaryImage">Main Image: </label>
					<input id="primaryImage" name="primaryImage" type="file" accept="image/*" /> 
					<div id="secondaryImagePreviewer">
					</div>
					<label for="secondaryImage">Secondary Image: </label>
					<input id="secondaryImage" name="secondaryImage" type="file" accept="image/*" /> 
				</fieldset>
				<!-- SUBMIT -->
				<input type="hidden" value="completeRegistration" name="action" />
				<input type="submit" value="Finish registration" /> 
			</form>
		</div>
	</div>
	<?php
	}else{
	?>
	<div id="profile">
		<div id="personalInfo">
			<?php
				$noPicUrl = $GLOBALS['noPicImgUrl'];
				$info = getUserInformation(getLoggedInUser());
				$firstName = $info['first_name'];
				$secondName = $info['second_name'];
				$firstLastname = $info['first_lastname'];
				$secondLastname = $info['second_lastname'];
				$postcode = $info['postcode'];
				$address = $info['address'];
				$gender = $info['gender'];
				$dateOfBirth = $info['date_of_birth'];
				$dateOfBirth = formatDateString($dateOfBirth, 'Y-m-d', 'm/d/Y');
				$age = getAge($dateOfBirth);
				$firstImageUrl = $info['first_image_url'];
				$secondImageUrl = $info['second_image_url'];
				echo "<div id=\"profileImageContainer\">";
				echo "<img src=\"".($firstImageUrl == "" ? ($secondImageUrl == "" ? $noPicUrl : $secondImageUrl) : $firstImageUrl)."\" />";
				echo "</div>";
				echo "<div id=\"infoContainer\">";
				echo "<p>Name: $firstName".($secondName == "" ? "": " $secondName") ." $firstLastname".($secondLastname == "" ? "": " $secondLastname")."</p>";
				echo "<p>age: $age</p>";
				echo "</div>";
			?>
		</div>
	</div>
		<?php
			if(true || listingExists(getLoggedInUser())){
				$listing = getListing(getLoggedInUser());
				$listing = $listing[0];
				//print_r($listing);
				$pk = $listing['pk'];
				$type = $listing['result_type_fk'];
				$title = $listing['title'];
				$image_url = $listing['image_url'] == "" ? $GLOBALS['noPicImgUrl'] : $listing['image_url'];
				$telephone = $listing['telephone'];
				$description = $listing['description'];
				$price = $listing['price'];
				$user = $listing['user_fk'];
				$email = $listing['email'];
				$webpage = $listing['webpage'];
				$roomType = $listing['room_type_fk'];
				$bedType = $listing['bed_type_fk'];
				$accomodates = $listing['accomodates'];
				$bedrooms = $listing['bedrooms'];
				$beds = $listing['beds'];
				$extraPeople = $listing['extra_people'];
				$weekPrice = $listing['week_price'];
				$monthPrice = $listing['month_price'];
				$cancellationFee = $listing['cancellation_fee'];
				$rules = $listing['rules'];
				$cancellationType = $listing['cancellation_type_fk'];
				//$address = ($listing['house'] == "" ? "" : $listing['house']).($listing['street'] == "" ? "" : $listing['street']).($listing['district'] == "" ? "" : $listing['district']).($listing['city'] == "" ? "" : $listing['city']);
				$postcode = $listing['postcode'];
				$city = $listing['city'];
				$street = $listing['street'];
				$house = $listing['house'];
				$district = $listing['district'];
				$rating = $listing['rating'];
				$lat = $listing['lat'];
				$lng = $listing['lng'];
				$addressPk = $listing['addressPk'];
				$locationPk = $listing['locationPk'];
		?>
		<div id="listingFormContainer">
			<form method="post" enctype="multipart/form-data" id="listingForm" action="listingLogic.php">
				<label for="typeOfListing">Type of Listing: </label>
				<select name="typeofListing" id="typeofListing">
				  <?php
				  	displayListingCathegories($type);
				  ?>
				</select>
				<div id="listingFormBody">
					<!--NAME OF LISTING -->
					<label for="nameListing">Name: </label>
					<input type="text" name="name" id="nameListing" value="<?php echo "$title"; ?>"/><br>
					<label for="descriptionListing">Description: </label>
					<textarea name="description" id="descriptionListing"><?php echo "$description"; ?></textarea> <br>
					<!--POSTCODE -->
					<label for="postcodeListing">Postcode: </label>
					<input type="text" name="postcode" id="postcodeListing" value="<?php echo "$postcode"; ?>"/><br>
					<!--FULL ADDRESS -->
					<label for="cityListing">City: </label>
					<input type="text" name="city" id="cityListing" value="<?php echo "$city"; ?>"/><br>
					<label for="areaListing">District/Area: </label>
					<input type="text" name="area" id="areaListing" value="<?php echo "$district"; ?>"/><br>
					<label for="streetNameListing">Street Name: </label>
					<input type="text" name="street" id="streetNameListing" value="<?php echo "$street"; ?>"/><br>
					<label for="houseNumberListing">House Number (this remains private): </label>
					<input type="text" name="houseNumber" id="houseNumberListing" value="<?php echo "$house"; ?>"/><br>
					<input type="hidden" id="coordsLatListing" name="lat" value="<?php echo "$lat"; ?>">
					<input type="hidden" id="coordsLngListing" name="lng" value="<?php echo "$lng"; ?>">
					<!--TELEPHONE NUMBER -->
					<label for="telephoneListing">Telephone: </label>
					<input type="number" name="telephone" id="telephoneListing" value="<?php echo "$telephone"; ?>"/><br>
					<!--EMAIL -->
					<label for="emailListing">Email: </label>
					<input type="email" name="email" id="emailListing" value="<?php echo "$email"; ?>"/><br>
					<!--WEBPAGE ADDRESS -->
					<label for="webpageAddressListing">Webpage Address: </label>
					<input type="text" name="webpage" placeholder="http://www.mysite.com" id="webpageAddressListing" <?php echo ($webpage != "" ? "value=\"$webpage\"" : "");?>/><br>
					<!--TYPE OF ROOM -->
					<label for="roomTypeListing">Room Type: </label>
					<select name="roomType" id="roomTypeListing">
					  <?php
					  	displayRoomTypes($roomType);
					  ?>
					</select><br>
					<!--TYPE OF BED -->
					<label for="bedTypeListing">Bed Type: </label>
					<select name="bedType" id="bedTypeListing">
					  <?php
					  	displayBedTypes($bedType);
					  ?>
					</select><br>
					<!--NUMBER OF ACCOMODATES -->
					<label for="accomodatesListing">Number of Accomodates</label>
					<input type="text" name="accomodates" id="accomodatesListing" value="<?php echo "$accomodates"; ?>" /><br>
					<!--BEDROOMS -->
					<label for="bedroomsListing">Bedrooms: </label>
					<input type="text" name="bedrooms" id="bedroomsListing" value="<?php echo "$bedrooms"; ?>"/><br>
					<!--BEDS -->
					<label for="bedsListing">Beds: </label>
					<input type="text" name="beds" id="bedsListing" value="<?php echo "$beds"; ?>" /><br>
					<!--EXTRA PEOPLE -->
					<label for="extraPeopleListing">Extra People: </label>
					<select name="extraPeople" id="extraPeopleListing">
					  <option value="">select a value</option> 
					  <option value="1" <?php printSelected($extraPeople, "1"); ?>>allowed</option>
					  <option value="0" <?php printSelected($extraPeople, "0"); ?>>not allowed</option>
					</select><br>
					<!--PRICE -->
					<label for="priceListing">Price: </label>
					<input type="number" name="price" id="priceListing" value="<?php echo "$price"; ?>"/><br>
					<!--WEEKLY PRICE -->
					<label for="weekPriceListing">Weekly Price: </label>
					<input type="number" name="weekPrice" id="weekPriceListing" value="<?php echo "$weekPrice"; ?>"/><br>
					<!--MONTHLY PRICE -->
					<label for="monthPriceListing">Monthly Price: </label>
					<input type="number" name="monthPrice" id="monthPriceListing" value="<?php echo "$monthPrice"; ?>"/><br>
					<!--CANCELLATION -->
					<label for="cancellationListing">Cancellation</label>
					<select name="cancellation" id="cancellationListing">
					  <?php
					  	displayCancellationTypes($cancellationType);
					  ?>
					</select><br>
					<label for="cancellationFeeListing">Cancellation Fee:</label>
					<input type="number" name="cancellationFee" id="cancellationFeeListing" value="<?php echo "$cancellationFee"; ?>"/><br>
					<!--HOUSE RULES -->
					<label for="houseRulesListing">House Rules</label>
					<textarea name="rulesHouse" id="houseRulesListing"><?php echo ($type == "1" ? $rules : ""); ?></textarea><br>
					<!--HOTEL RULES -->
					<label for="hotelRulesListing">Hotel Rules</label>
					<textarea name="rulesHotel" id="hotelRulesListing"><?php $type == "2" ? $rules : ""; ?></textarea><br>
					<!--HOTEL RATING -->
					<label for="hotelRatingListing">Hotel Rating</label>
					<select name="hotelRating" id="hotelRatingListing">
					  <option value="">select a value</option>
					  <option value="1" <?php printSelected($rating, "1"); ?>>1 star</option>
					  <option value="2" <?php printSelected($rating, "2"); ?>>2 star</option>
					  <option value="3" <?php printSelected($rating, "3"); ?>>3 star</option>
					  <option value="4" <?php printSelected($rating, "4"); ?>>4 star</option>
					  <option value="5" <?php printSelected($rating, "5"); ?>>5 star</option>
					</select><br>

					<label for="imageUrlListing">Image: </label>
					<input id="imageUrlListing" name="imageUrl" type="file" accept="image/*" /> 
					<div id="imageUrlListingPreviewer" <?php echo ($image_url != "" ? "style=\"background-image: url('$image_url'); display:block;\"" : ""); ?>>
					</div>
					<input type="hidden" name="exantLocation" value="<?php echo $locationPk; ?>">
					<input type="hidden" name="exantAddress" value="<?php echo $addressPk; ?>">
					<input type="hidden" name="exant" value ="<?php echo $pk; ?>"> 
					<input type="hidden" name="user" value="<?php echo getLoggedInUser(); ?>">
					<input type="hidden" name="action" value="save"/>
					<input type="submit" value="submit" />
				</div>
			</form>
		</div>
		<?php
			}else{

		?>
		<?php
			}//end of else/	if(listingExists(getLoggedInUser()))
		?>
	<?php
	}//End of else/if(!$addionalInfoExists)
	?>
</body>
</html>